﻿using System.IO;
using System.Net.Http;
using System.Numerics;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Win32;
using MiniMax.Library;

namespace AiTool_Window
{
    /// <summary>
    /// Text2Audio.xaml 的交互逻辑
    /// </summary>
    public partial class Text2Audio : Page
    {
        public Text2Audio()
        {
            InitializeComponent();
        }

        private void PageInit()
        {
            //获取应用程序根目录，获取所有配置文件
            string RootPath = AppDomain.CurrentDomain.BaseDirectory;
            string SettingPath = Path.Combine(RootPath,"Doc","Setting");
            if (!Directory.Exists(SettingPath)) 
            {
                MessageBox.Show("未找到任何配置文件！");
                return;
            }
            string[] SettingFiles = Directory.GetFiles(SettingPath, "*.json");
            Dictionary<string, string> dctConfig = new Dictionary<string, string>();
            foreach (string fileFullPath in SettingFiles)
            {
                dctConfig.Add(Path.GetFileNameWithoutExtension(fileFullPath),fileFullPath);
            }
            cbxNowConfig.ItemsSource = dctConfig;
            cbxNowConfig.DisplayMemberPath = "Key";
            cbxNowConfig.SelectedValuePath = "Value";
            if (cbxNowConfig.Items.Count>0)
            {
                cbxNowConfig.SelectedIndex = 0;
            } 
            
            StringBuilder txtConfig = new StringBuilder();
            txtConfig.AppendLine("功能类型1，替换声调：[\"燕少飞/(yan4)(shao3)(fei1)\"]");
            txtConfig.AppendLine("功能类型2，替换字符：[\"omg/oh my god\",\"=/等于\"]");
            txtConfig.AppendLine("声调用数字代替，一声（阴平）为1，二声（阳平）为2，三声（上声）为3，四声（去声）为4），轻声为5");
            this.txtConfig.ToolTip = txtConfig.ToString();

            Dictionary<string, string> dct音色 = new Dictionary<string, string>();
            dct音色.Add("青涩青年音色", "male-qn-qingse");
            dct音色.Add("精英青年音色", "male-qn-jingying");
            dct音色.Add("霸道青年音色", "male-qn-badao");
            dct音色.Add("青年大学生音色", "male-qn-daxuesheng");
            dct音色.Add("少女音色", "female-shaonv");
            dct音色.Add("御姐音色", "female-yujie");
            dct音色.Add("成熟女性音色", "female-chengshu");
            dct音色.Add("甜美女性音色", "female-tianmei");
            dct音色.Add("男性主持人", "presenter_male");
            dct音色.Add("女性主持人", "presenter_female");
            dct音色.Add("男性有声书1", "audiobook_male_1");
            dct音色.Add("男性有声书2", "audiobook_male_2");
            dct音色.Add("女性有声书1", "audiobook_female_1");
            dct音色.Add("女性有声书2", "audiobook_female_2");
            dct音色.Add("青涩青年音色-beta", "male-qn-qingse-jingpin");
            dct音色.Add("精英青年音色-beta", "male-qn-jingying-jingpin");
            dct音色.Add("霸道青年音色-beta", "male-qn-badao-jingpin");
            dct音色.Add("青年大学生音色-beta", "male-qn-daxuesheng-jingpin");
            dct音色.Add("少女音色-beta", "female-shaonv-jingpin");
            dct音色.Add("御姐音色-beta", "female-yujie-jingpin");
            dct音色.Add("成熟女性音色-beta", "female-chengshu-jingpin");
            dct音色.Add("甜美女性音色-beta", "female-tianmei-jingpin");

            this.cbx音色.ItemsSource = dct音色;
            cbx音色.SelectedValuePath = "Value";
            cbx音色.DisplayMemberPath = "Key";
            //根据Config设定默认选项
            cbx音色.SelectedIndex = 0;



            cbx音频格式.Items.Add("mp3");
            cbx音频格式.Items.Add("wav");
            cbx音频格式.Items.Add("pcm");
            cbx音频格式.Items.Add("flac");
            cbx音频格式.Items.Add("aac");
            cbx音频格式.SelectedIndex = 0;

            cbx采样率.Items.Add(16000);
            cbx采样率.Items.Add(24000);
            cbx采样率.Items.Add(32000);
            cbx采样率.SelectedItem = 32000;

            cbx比特率.Items.Add(32000);
            cbx比特率.Items.Add(64000);
            cbx比特率.Items.Add(128000);
            cbx比特率.SelectedItem = 128000;
        }

        private void sli音量_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            txt音量.Text = Math.Round(e.NewValue, 2, MidpointRounding.ToZero).ToString();
        }

        private void sli语速_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            txt语速.Text = Math.Round(e.NewValue, 2, MidpointRounding.ToZero).ToString();
        }

        private void sli语调_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            txt语调.Text = Math.Floor(e.NewValue).ToString();
        }

        private async void btnSend_Click(object sender, RoutedEventArgs e)
        {
            txtAudioLink.Text = "";
            txtSubtitleLink.Text = "";
            T2A_Pro t2A_Pro = new T2A_Pro();
            T2A_ProRequest request = new T2A_ProRequest();
            request.header.Authorization = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJHcm91cE5hbWUiOiLokaPplYciLCJVc2VyTmFtZSI6IuiRo-mVhyIsIkFjY291bnQiOiIiLCJTdWJqZWN0SUQiOiIxNzU5NDkzNjg3ODczNjQyOTQ3IiwiUGhvbmUiOiIxNzMyMDAxODE5MSIsIkdyb3VwSUQiOiIxNzU5NDkzNjg3ODY1MjU0MzM5IiwiUGFnZU5hbWUiOiIiLCJNYWlsIjoiNzA2NTg3NzEzQHFxLmNvbSIsIkNyZWF0ZVRpbWUiOiIyMDI0LTA1LTI3IDE4OjQzOjA0IiwiaXNzIjoibWluaW1heCJ9.pXUAUQSYAJo60jia7-feBX1MeuEspTv1B3osXFtTdZsFz2OJrMFPLpH0jYCZVIMiixAXDxBcORfDU5xvtbJPjp4ewZ_NrHYfCP4oYbrdwGAzava0nv3Kp4IGoFmeWBYF7hc8CeNVFgG4_ND6mBRMEEAiud7sqIxopM9a89Nqkwbs4_EDFOwrCtGuj-VJj3VfVlsh_Bj1ZCgjvAyUzJIrXgXAzoYrEF4SsKnbi7am-gJ2JyD8HLxbmV7VvrVZEO6CJPGyOsQ_h4rBjyG8DCcF9WNGpU2fhX7zopxz4-AAnli4g0lbv7zR1Jj77t_x1rNe9eJp3KKNLaEtrzb8Qx1wMA";
            request.header.Content_Type = "application/json";

            request.groupId = "1759493687865254339";

            request.data.voice_id = cbx音色.SelectedValue.ToString();
            bool checkSpeed = double.TryParse(txt语速.Text, out double dSpeed);
            request.data.speed = checkSpeed ? dSpeed : 1.0;
            bool checkVol = double.TryParse(txt音量.Text, out double dVol);
            request.data.vol = checkVol ? dVol : 1.0;
            request.data.output_format = cbx音频格式.SelectedItem.ToString();
            bool checkPitch = int.TryParse(txt语调.Text, out int dPitch);
            request.data.pitch = checkPitch ? dPitch : 0;
            request.data.text = txtInput.Text;
            request.data.audio_sample_rate = (int)cbx采样率.SelectedItem;
            request.data.bitrate = (int)cbx比特率.SelectedItem;

            if (string.IsNullOrEmpty(txtConfig.Text))
            {
                request.data.char_to_pitch = null;
            }
            else 
            {
                request.data.char_to_pitch = txtConfig.Text.Split('\n');
            }
            
            T2A_ProRequestResponse response = await t2A_Pro.Send(request);

            txtAudioLink.Text = response.audio_file ?? "";
            txtSubtitleLink.Text = response.subtitle_file ?? "";
        }

        private void btn_OpenFile_Click(object sender, RoutedEventArgs e)
        {

        }

        private async void btnDownloadAudio_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(txtAudioLink.Text))
            {
                MessageBox.Show("请先生成下载链接！");
                return;
            }
            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage httpResponse = await client.GetAsync(txtAudioLink.Text);

                if (httpResponse.IsSuccessStatusCode) 
                {
                    using (Stream contentStream = await httpResponse.Content.ReadAsStreamAsync())
                    {
                        SaveFileDialog fileDialog = new SaveFileDialog();

                        #region 添加预定保存路径(待补充)

                        #endregion

                        fileDialog.FileName = "."+cbx音频格式.Text;
                        fileDialog.Filter = "mp3|*.mp3|wav|*.wav|pcm|*.pcm|flac|*.flac|aac|*.aac";
                        if (fileDialog.ShowDialog()==true)
                        {
                            using (FileStream fs = new FileStream(fileDialog.FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                            {
                                await contentStream.CopyToAsync(fs);
                            }
                        }
                    }

                }
                else
                {
                    MessageBox.Show($"下载失败，状态码：{httpResponse.StatusCode}");
                }
            }
        }

        private async void btnDownloadCaption_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(txtSubtitleLink.Text))
            {
                MessageBox.Show("请先生成下载链接！");
                return;
            }
            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage httpResponse = await client.GetAsync(txtSubtitleLink.Text);

                if (httpResponse.IsSuccessStatusCode)
                {
                    using (Stream contentStream = await httpResponse.Content.ReadAsStreamAsync())//title文件
                    {
                        SaveFileDialog fileDialog = new SaveFileDialog();

                        #region 添加预定保存路径(待补充)

                        #endregion

                        fileDialog.FileName = ".srt";
                        fileDialog.Filter = "SRT字幕|*.srt";
                        if (fileDialog.ShowDialog() == true)
                        {
                            T2A_Pro.Title2Srt_Save(contentStream, fileDialog.FileName);
                            MessageBox.Show("保存成功！");
                        }
                    }
                }
                else
                {
                    MessageBox.Show($"下载失败，状态码：{httpResponse.StatusCode}");
                }
            }
        }

        private void btnSetting_Click(object sender, RoutedEventArgs e)
        {
            Text2AudioSetting window = new Text2AudioSetting();
            if (window.ShowDialog()==true)
            {

            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            PageInit();
        }

        private void cbxNowConfig_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (((ComboBox)sender).SelectedValue!=null)
            {

            }
        }
    }
}
